import React, { Component } from 'react';
import {
  StyleSheet, View, TouchableOpacity, Text, Platform, DeviceEventEmitter, ScrollView,
} from 'react-native';
import OpenFile from 'react-native-doc-viewer';
import produce from 'immer';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Theme from '../../../native-base-theme/variables/commonColor';
import * as techDocService from '../../../services/techDoc';
import { UtilToast } from '../../../utils/util-method';

const mdata = [{
  label: '技术性能',
  icon: 'accusoft',
  index: 1,
}, {
  label: '操作手册',
  icon: 'book',
  index: 2,
}, {
  label: '维修手册',
  icon: 'bible',
  index: 3,
}, {
  label: '配套设备',
  icon: 'calculator',
  index: 4,
}, {
  label: '润滑标准',
  icon: 'buffer',
  index: 5,
}, {
  label: '变更记录',
  icon: 'calendar-check',
  index: 6,
}, {
  label: '备件更换历史',
  icon: 'calendar-edit',
  index: 7,
}];

// , {
//   label: '备件库存查询',
//   icon: 'calendar-edit',
//   index: 8,
// }

class assetDoc extends Component {
  maintenanceManual = '';

  operationManual = '';

  constructor(props) {
    super(props);
    this.state = {
      isError: false,
    };
  }

  _getPage = () => {
    const list = [];
    mdata.forEach(item => {
      list.push(
        <TouchableOpacity icon onPress={() => this._onPress(item)} key={item.index} style={styles.item}>
          <Icon name={item.icon} size={26} color="white" />
          <Text style={{ fontSize: Theme.myNormalFontSize, color: 'white', marginLeft: 8 }}>
            {item.label}
          </Text>
        </TouchableOpacity>
      );
    });
    return list;
  }

  _onPress = (item) => {
    if (item.index == 1) {
      // global.navigation.navigate({ routeName: 'TechPerformance', params: { datas: this.props.data } });
      this.toTechPerformance();
    } else if (item.index == 2 || item.index == 3) {
      // eslint-disable-next-line no-unused-expressions
      // this.operationManual ? this.showPopover(item.index) : this.getManualDatas(item.index);
      this.getManualDatas(item.index);
    } else if (item.index == 4) {
      this.toCorollaryEquipment();
    } else if (item.index == 5) {
      this.toLubricationStandard();
    } else if (item.index == 6) {
      this.toChangeRecord();
    } else if (item.index == 7) {
      this.toChangeHistory();
    } else if (item.index == 8) {
      this.toSparePartsInventory();
    }
  }

  // 技术性能
  toTechPerformance = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'TechPerformance',
        titleStr: '技术性能',
        datas: this.props.data,
      },
    });
  }

  // 润滑标准
  toLubricationStandard = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'LubricationStandard',
        titleStr: '润滑标准',
        datas: this.props.data,
      },
    });
  }

  // 配套设备
  toCorollaryEquipment = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'CorollaryEquipment',
        titleStr: '配套设备',
        datas: this.props.data,
      },
    });
  }

  // 变更记录
  toChangeRecord = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'ChangeRecord',
        titleStr: '变更记录',
        datas: this.props.data,
      },
    });
  }

  // 备件更换历史
  toChangeHistory = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'ChangeHistory',
        titleStr: '备件更换历史',
        datas: this.props.data,
      },
    });
  }

  // 备件库存
  toSparePartsInventory = () => {
    global.navigation.navigate({
      routeName: 'TechPage',
      params: {
        type: 'SparePartsInventory',
        titleStr: '备件库存',
        datas: this.props.data,
      },
    });
  }

  getManualDatas = async (index) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const datas = this.props.data;
      if (datas && datas.objType) {
        const data = await techDocService.getManual({ objType: datas.objType });
        // const data = await techDocService.getTechPerformance({ objType: 'RX_240ZLJZKGZZ' });
        // DeviceEventEmitter.emit('showLoading', false);
        if (data) {
          // this.setState(produce(draft => {
          //   draft.datas = data;
          // }));
          this.operationManual = data.operationManual;
          this.maintenanceManual = data.maintenanceManual;
          this.showPopover(index);
        } else {
          UtilToast(index === 2 ? '该设备暂无操作手册信息' : '该设备暂无维修手册信息', 'danger');
          DeviceEventEmitter.emit('showLoading', false);
        }
      } else {
        DeviceEventEmitter.emit('showLoading', false);
        UtilToast('没有设备信息', 'danger');
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  showPopover = async (index) => {
    let murl = '';
    if (index === 2) {
      murl = this.operationManual;
    } else if (index === 3) {
      murl = this.maintenanceManual;
    }

    if (!murl) {
      UtilToast(index === 2 ? '该设备暂无操作手册信息' : '该设备暂无维修手册信息', 'danger');
      DeviceEventEmitter.emit('showLoading', false);
      return;
    }

    // DeviceEventEmitter.emit('showLoading', true);
    if (Platform.OS === 'ios') {
      OpenFile.openDoc([{
        url: murl,
        fileNameOptional: 'filename',
      }], (error, url) => {
        if (error) {
          // this.setState({ animating: false });
          console.log(error);
        } else {
          // this.setState({ animating: false });
          console.log(url);
        }
        DeviceEventEmitter.emit('showLoading', false);
      });
    } else {
      // Android
      OpenFile.openDoc([{
        url: murl, // Local "file://" + filepath
        fileName: 'sample',
        cache: false,
        fileType: 'pdf',
      }], (error, url) => {
        if (error) {
          // this.setState({animating: false});
          console.error(error);
        } else {
          // this.setState({animating: false});
          console.log(url);
        }
        DeviceEventEmitter.emit('showLoading', false);
      });
    }
  }

  render() {
    return (
      <ScrollView style={{ backgroundColor: Theme.myPrimary }}>
        <View style={styles.tabContent}>
          {this._getPage()}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  tabContent: {
    backgroundColor: Theme.myPrimary,
    color: '#ffffff',
    flexDirection: 'column',
    width: '100%',
    flex: 1,
  },
  item: {
    paddingLeft: 8,
    paddingRight: 8,
    paddingTop: 10,
    flexDirection: 'row',
    paddingBottom: 10,
    alignItems: 'center',
    borderBottomColor: 'rgba(255,255,255,0.2)',
    borderBottomWidth: 1,
  },
});

export default assetDoc;
